var express = require('express');
var router = express.Router();
var Banner = require("../models/banner");

var multer  = require('multer');
var upload = multer({ dest: 'upload/' })
var shangchuan = require('../models/uplodaTengxun_cos.js');


//上传广告
router.post('/addBanner', upload.array("url"),async function(req, res, next) {

    let imageSrc = await shangchuan(req.files[0]);

    var param = {
        goodsId :req.body.goodsId,
        goodsName:req.body.goodsName,
        url:imageSrc
    };
    Banner.create( param ,function(err,doc){
        if(err){
            res.json({
                status:"1",
                msg:err.message,
                result: ""
            })
        }else{
            if(doc){
                res.json({
                    status:"0",
                    msg:"添加成功",
                    result: "suc"
                })
            }
        }
    })

})

//获取广告数据
router.get('/getBanner', function(req, res, next) {
    // let page = parseInt(req.param("page"));
    // let pageSize = parseInt(req.param("pageSize"));
    // let sort = req.param("sort");
    // let skip = (page-1)*pageSize;
    // let params = {};
    // let goodsModel = Goods.find(params).skip(skip).limit(pageSize);
    //
    // goodsModel.sort({"salePrice" : sort});



    var model = Banner.find();
    model.exec(function(err,result){
        if(err){
            res.json({
                status:"1",
                msg:err.message
            })
        }else{

            res.json({
                status:"0",
                msg:"",
                result:{
                    count:result.length,
                    list:result
                }
            })
        }
    });
});

//删除广告
router.post('/delBanner', function(req, res, next) {
    Banner.remove({"_id":req.body.id}, function (err,doc){
        if(err){
            res.json({
                status:"1",
                msg:err.message,
                result: ""
            })
        }else{
            if(doc){
                res.json({
                    status:"0",
                    msg:"删除成功",
                    result: "suc"
                })
            }
        }
    });
});



module.exports = router;
